package org.nidy.programexercise.FileExercise;

import java.io.File;
import java.util.HashMap;

public class FileHandle {
    public static HashMap<String,Integer> getFileCount(File src){
        HashMap<String,Integer>countMap=new HashMap<>();
        File[]files=src.listFiles();
        for(File file:files){
            if(file.isFile()){
                String fileName=file.getName();
                String[] fileArr=fileName.split("\\.");
                if(fileArr.length>=2){
                    String endName=fileArr[fileArr.length-1];
                    if(countMap.containsKey(endName)){
                        int count=countMap.get(endName);
                        countMap.put(endName,count+1);
                    }else{
                        countMap.put(endName,1);
                    }
                }
            } else if (file.isDirectory()) {
                HashMap<String, Integer> sonMap = getFileCount(file);
                sonMap.entrySet().forEach(e->{
                    String key=e.getKey();
                    int value=e.getValue();
                    if (countMap.containsKey(key)) {
                        int count = countMap.get(key);
                        countMap.put(key, count + value);
                    } else {
                        countMap.put(key, value);
                    }
                });
            }

        }
        return countMap;
    }
}
